<template>
  <div>
    <div class="release-box">
      <el-form :model="form"
               label-width="auto"
               ref="form"
               :rules="rules">
        <el-form-item label="发包方" prop="username">
          <el-input type="text" v-model="form.username" disabled/>
        </el-form-item>
        <el-form-item label="任务名称" prop="taskname">
          <el-input data-testid="task-name" type="text" placeholder="请输入任务名称" v-model="form.taskname"/>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input
              data-testid="task-description"
              type="textarea"
              :autosize="{ minRows: 4 }"
              placeholder="请在此处填写测试任务整体描述"
              maxlength="200"
              show-word-limit
              v-model="form.description">
          </el-input>
        </el-form-item>
        <el-form-item label="需求人数" prop="need_num">
          <el-row type="flex">
            <el-input-number
                data-testid="task-number"
                v-model="form.need_num" :min="1" :max="1000">
            </el-input-number>
          </el-row>
        </el-form-item>
        <el-form-item label="待测应用上传">
          <el-row type="flex">
            <el-upload
                data-testid="task-app-file"
                ref="upload"
                action="#"
                :on-change="handleChangeExe"
                :auto-upload="false">
              <el-button slot="trigger" size="small" type="goon">选取文件</el-button>
            </el-upload>
          </el-row>
        </el-form-item>
        <el-form-item label="描述文档上传">
          <el-row type="flex">
            <el-upload
                data-testid="task-description-file"
                ref="upload"
                action="#"
                :on-change="handleChangeGuide"
                :auto-upload="false">
              <el-button slot="trigger" size="small" type="goon">选取文件</el-button>
            </el-upload>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-card style="margin: 30px">
            <task-map
                v-model="form.subTasks"
                :mode="mode"
                @click-node="handleClickNode"
                :get-empty-node="handleGetEmptyNode"
            >
            </task-map>
          </el-card>
        </el-form-item>
        <el-form-item>
          <el-button class="btn" type="goon" @click="onSubmit('form')">发布任务</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :visible.sync="subTaskDialogVisible"
      width="1150px"
      :destroy-on-close="true"
      >
      <span>
        <subTaskRelease :sub-task="selectedSubTask"></subTaskRelease>
      </span>
      <span slot="footer" class="dialog-footer">
      </span>
    </el-dialog>
  </div>

</template>

<script>
import TaskMap from "@/components/new/task-map/TaskMap";
import subTaskRelease from "@/components/boss/new/subTaskRelease";
import {Debounce} from "@/utils/Debounce";
import {getUserBalance} from "@/api/user";
import {createCollaborationTask} from "@/api/task";
import {uploadFile} from "@/api/file";
import {createTaskFile} from "@/api/task";
export default {
  name: "ReleaseMultiUserTask",
  components: {TaskMap,subTaskRelease},
  data(){
    return {
      form: {
        username: sessionStorage.getItem("username"),
        taskname: "",
        description: "",
        need_num: "",
        subTasks: []
      },
      selectedSubTask: {},
      rules: {
        taskname: [
          {required: true, message: '请填写任务名称', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请填写任务描述', trigger: 'blur'}
        ]
      },
      mode:"edit",
      clickNodeEvents: [],
      subTaskDialogVisible: false,


    }
  },
  methods:{
    handleClickNode(nodeId){
      this.selectedSubTask = this.form.subTasks.filter(node => node.id === nodeId)[0];
      console.log(this.selectedSubTask)
      this.subTaskDialogVisible = true;
    },
    handleGetEmptyNode(){
      return {
        id: Math.floor(Math.random() * 10000) * 10000 + (new Date().getTime() % 10000),
        taskname:'',
        deviceRequirement: {
          osList: [],
          minRam: 4,
          maxRam: 16,
          processorArchitectureList: []
        },
        type:'',
        deadline:'',
        description:'',
        reportPrice: 0,
        dependencies: [],
      }
    },
    handleChangeExe(file, fileList) {
      if (fileList.length > 1) {
        fileList.shift()
      }
      this.exeFileList = fileList
      console.log(fileList)
    },


    handleChangeGuide(file, fileList) {
      if (fileList.length > 1) {
        fileList.shift()
      }
      this.guideFileList = fileList
      console.log(fileList)
    },

    transformSubtasks(subTasks){
      const taskMap = new Map();
      for(let i = 0; i < subTasks.length; i++){
        taskMap.set(subTasks[i].id, i);
      }
      return subTasks.map(subTask => {
        return {
          ...subTask,
          dependencies: subTask.dependencies.map(id => taskMap.get(id)),
          id: undefined
        }
      })
    },

    onSubmit: Debounce(function (formName) {
      console.log(this.form);
      this.$confirm('确定发布任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      this.$refs[formName].validate((valid) => {
          if(valid){
            // 余额检查：获取当前余额
            const userId = sessionStorage.getItem('userid');
            let totalPrice = 0;
            for(let i=0;i<this.form.subTasks.length;i++){
              totalPrice+=this.form.subTasks[i].reportPrice;
            }
            getUserBalance(userId).then(res=>{
              if(res.code === 200){
                this.balance = res.data;
                console.log(this.balance);
                // if 余额不足，让它充值
                if(this.balance<totalPrice*this.form.need_num){
                  this.$confirm('您的余额不足，当前余额：'+this.balance+'，是否前往充值？', '提示', {
                    confirmButtonText: '充值',
                    cancelButtonText: '取消',
                    type: 'error'
                  }).then(() => {
                    this.dialogVisible=true;
                  }).catch(()=>{
                  })
                }
                // else 发布任务
                else{
                  const payload = {...this.form, subTasks: this.transformSubtasks(this.form.subTasks)};

                  this.handleReleaseTask(payload);
                }
              }
              else{
                alert('balance loading failed'+res.msg);
              }
            });
          }
          else {
              this.$message.error('发布失败，请检查您的信息！')
              return false;
          }
        });
      }).catch(() => {
      })
    }, 1000),


    async handleReleaseTask(payload) {
      //todo 任务发布后需要扣款，更新余额和交易记录
      if (this.exeFileList.length < 1 || this.guideFileList < 1) {
        this.$message.error('发布失败，请选择相关文件')
        return
      }

      const taskRes = await createCollaborationTask(payload);

      if (taskRes.code === 200) {
        this.$message.success('发布成功！');
        await this.$router.push('/boss/mytasks/executing');
      } else {
        this.$message.error('发布失败！服务器出错');
      }

      // 上传可执行文件
      const formDataExe = new window.FormData();
      formDataExe.append("file", this.exeFileList[0].raw);
      let res = await uploadFile(formDataExe);

      // 写入数据库
      if (res.code === 200) {
        const fileInfo = {
          taskId: taskRes.data,
          url: res.data.name,
          type: res.data.type,
          size: res.data.size,
          kind: "2",
          name: res.data.name
        };

        createTaskFile(fileInfo).then(res => {
          console.log(res);
        });
      }

      //上传文档
      const formDataGuide = new window.FormData();
      formDataGuide.append("file", this.guideFileList[0].raw);
      res = await uploadFile(formDataGuide);

      //写入数据库
      if (res.code === 200) {
        const fileInfo = {
          taskId: taskRes.data,
          url: res.data.name,
          type: res.data.type,
          size: res.data.size,
          kind: "3",
          name: res.data.name
        };

        createTaskFile(fileInfo).then(res => {
          console.log(res);
        });
      }
    },

  },

}
</script>

<style scoped>

.release-box {
  border: 1px solid #DCDFE6;
  width: 1000px;
  margin: 2% auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 8px #909399;

  background-color: #f8f8f8;
}

</style>
